플로이드#134
Conversation
There was a problem hiding this comment.
Code Review
This pull request implements the Floyd-Warshall algorithm to solve the all-pairs shortest path problem. The feedback provided focuses on optimizing the algorithm's performance and improving code readability. Specifically, it is recommended to initialize self-loop costs to zero outside the main triple loop, simplify the path update logic using the min function, and replace the inefficient removeFirst() call with array slicing during the output phase to avoid unnecessary
| @@ -0,0 +1,42 @@ | |||
| let n = Int(readLine()!)! | |||
| let m = Int(readLine()!)! | |||
| var graph = Array(repeating:Array(repeating: Int.max, count: n + 1), count: n + 1) | |||
There was a problem hiding this comment.
그래프의 자기 자신으로 가는 경로(i == j)의 비용은 항상 0입니다. 이를 3중 반복문 내부에서 매번 확인하는 대신, 초기화 시점에 미리 0으로 설정하는 것이 효율적입니다.
| var graph = Array(repeating:Array(repeating: Int.max, count: n + 1), count: n + 1) | |
| var graph = Array(repeating: Array(repeating: Int.max, count: n + 1), count: n + 1) | |
| for i in 1...n { graph[i][i] = 0 } |
| for j in 1...n { | ||
| if i == j { graph[i][j] = 0 } | ||
| if graph[i][k] != Int.max && graph[k][j] != Int.max { | ||
| let cost = graph[i][k] + graph[k][j] | ||
| if graph[i][j] > cost { | ||
| graph[i][j] = cost | ||
| } | ||
| } | ||
| } |
| for i in 1..<graph.count { | ||
| graph[i].removeFirst() | ||
| let row = graph[i].map { $0 == Int.max ? "0" : String($0) }.joined(separator: " ") | ||
| print(row) |
There was a problem hiding this comment.
removeFirst()는 배열의 모든 요소를 앞으로 한 칸씩 당기는 작업이므로 graph[i][1...n])을 사용하면 원본을 유지하면서도 효율적으로 필요한 범위만 출력할 수 있습니다.
| for i in 1..<graph.count { | |
| graph[i].removeFirst() | |
| let row = graph[i].map { $0 == Int.max ? "0" : String($0) }.joined(separator: " ") | |
| print(row) | |
| for i in 1...n { | |
| let row = graph[i][1...n].map { $0 == Int.max ? "0" : String($0) }.joined(separator: " ") | |
| print(row) |
🔗 문제 링크
✔️ 소요된 시간
못품
📚 새롭게 알게된 내용
플로이드